package com.ruoyi.project.module.errorcodeCache.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.google.common.collect.Maps;
import com.ruoyi.project.config.AliyunOSSCoreProperties;
import com.ruoyi.project.module.task.ErrorCodeJson;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.shoukaiseki.apiview.common.util.Base62Decimal;
import org.shoukaiseki.apiview.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.module.errorcodeCache.domain.ErrorcodeCache;
import com.ruoyi.project.module.errorcodeCache.service.IErrorcodeCacheService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 错误代码缓存 信息操作处理
 * 
 * @author ruoyi
 * @date 2018-11-02
 */
@Controller
@RequestMapping("/module/errorcodeCache")
public class ErrorcodeCacheController extends BaseController
{
    private String prefix = "module/errorcodeCache";

    @Resource
	OSSClient ossClient;

	@Resource
	AliyunOSSCoreProperties aliyunOSSCoreProperties;

	@Autowired
	private IErrorcodeCacheService errorcodeCacheService;
	
	@RequiresPermissions("module:errorcodeCache:view")
	@GetMapping()
	public String errorcodeCache()
	{
	    return prefix + "/errorcodeCache";
	}
	
	/**
	 * 查询错误代码缓存列表
	 */
	@RequiresPermissions("module:errorcodeCache:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(ErrorcodeCache errorcodeCache)
	{
		startPage();
		if(!StringUtils.isEmpty(errorcodeCache.getSearchText())){
		    errorcodeCache.setSearchValue(errorcodeCache.getSearchText());
		}
        List<ErrorcodeCache> list = errorcodeCacheService.selectErrorcodeCacheList(errorcodeCache);
		return getDataTable(list);
	}
	
	/**
	 * 新增错误代码缓存
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存错误代码缓存
	 */
	@RequiresPermissions("module:errorcodeCache:add")
	@Log(title = "错误代码缓存", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(ErrorcodeCache errorcodeCache)
	{		
		return toAjax(errorcodeCacheService.insertErrorcodeCache(errorcodeCache));
	}

	/**
	 * 修改错误代码缓存
	 */
	@GetMapping("/edit/{apiErrorcodeCacheId}")
	public String edit(@PathVariable("apiErrorcodeCacheId") Integer apiErrorcodeCacheId, ModelMap mmap)
	{
		ErrorcodeCache errorcodeCacheTemp=new ErrorcodeCache();
		errorcodeCacheTemp.setApiErrorcodeCacheId(apiErrorcodeCacheId);
		ErrorcodeCache errorcodeCache = errorcodeCacheService.selectErrorcodeCacheById(errorcodeCacheTemp);
		mmap.put("errorcodeCache", errorcodeCache);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存错误代码缓存
	 */
	@RequiresPermissions("module:errorcodeCache:edit")
	@Log(title = "错误代码缓存", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(ErrorcodeCache errorcodeCache)
	{		
		return toAjax(errorcodeCacheService.updateErrorcodeCache(errorcodeCache));
	}
	
	/**
	 * 删除错误代码缓存
	 */
	@RequiresPermissions("module:errorcodeCache:remove")
	@Log(title = "错误代码缓存", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(errorcodeCacheService.deleteErrorcodeCacheByIds(ids));
	}

	@Resource
	ErrorCodeJson errorCodeJson;

	/**
	 * 生成json
	 */
	@Log(title = "错误代码JSON生成", businessType = BusinessType.GENCODE)
	@GetMapping("/export/json")
	public void genCode(HttpServletResponse response) throws IOException
	{
	    byte[] data=errorCodeJson.exportJson();
		String fielname = DigestUtils.md5Hex(data);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename="+fielname+".json");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");


		IOUtils.write(data, response.getOutputStream());
	}

	/**
	 * 上传至阿里云
	 * @throws IOException
	 */
	@Log(title = "错误代码JSON生成", businessType = BusinessType.GENCODE)
	@RequestMapping("/uploadAliyun/json")
	@ResponseBody
	public AjaxResult uploadAliyun() throws IOException
	{
		if (aliyunOSSCoreProperties.getBucketName()==null) {
			return error("配置BucketName不能为空(估计是未启用自动上传功能)");
		}

		byte[] data=errorCodeJson.exportJson();
		String fielname = DigestUtils.md5Hex(data);

		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("md5",fielname);
		jsonArray.add(jsonObject);
		byte[] bytes = jsonArray.toJSONString().getBytes();
		uploadFile(new ByteArrayInputStream(bytes), aliyunOSSCoreProperties.getBucketName(), "errorcode",  "errorcode.json");

		uploadFile(new ByteArrayInputStream(bytes), aliyunOSSCoreProperties.getBucketName(), "errorcode",  "errorcode");

		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
		uploadFile(byteArrayInputStream, aliyunOSSCoreProperties.getBucketName(), "errorcode/version", fielname + ".json");

		StringBuilder sb=new StringBuilder("上传成功");

		sb.append("<br>filename=").append(fielname).append(".json");

		return success(sb.toString());
	}


	public String uploadFile(InputStream inputStream, String bucketName, String path, String fileName) throws IOException {
		//创建上传Object的Metadata
		ObjectMetadata metadata = new ObjectMetadata();
		//上传的文件的长度
		metadata.setContentLength(inputStream.available());
		//指定该Object被下载时的网页的缓存行为
		metadata.setCacheControl("max-age=1");
		//指定该Object下设置Header
		metadata.setHeader("Pragma", "no-cache");
		metadata.setHeader("Expires", "1");
		//指定该Object被下载时的内容编码格式
		metadata.setContentEncoding("utf-8");
		//文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
		//如果没有扩展名则填默认值application/octet-stream
		metadata.setContentType("application/json");
		//指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
//		metadata.setContentDisposition("filename=" + fileName);
		//上传文件   (上传文件流的形式)
		PutObjectResult putResult = ossClient.putObject(bucketName, path +"/"+ fileName, inputStream,metadata);

		return putResult.getETag();
	}




	@PostMapping( "/parserBase62")
	@ResponseBody
	public Long parserBase62(@RequestParam String base62){
		HashMap<String,Integer> resultMap = Maps.newHashMap();
		long l = Base62Decimal.convertBase62ToDecimal(base62);

		return l;
	}


	@PostMapping( "/clear")
	@ResponseBody
	public int clear(){
		int l = errorcodeCacheService.clear();

		return l;
	}
}
